<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import type { FormInstance } from 'element-plus'
import { getChatList } from "@/api/message";
import { chatListQuery, chatListVO } from "@/api/message/types";
import ChatDetail from "@/views/chat-case/chat-list/components/chat-detail.vue";

const dialogVisible = ref(false);
const selectedChat = ref<{ visitorId: string; serviceName: string }>({
  visitorId: '',
  serviceName: ''
});

const loading = ref(false); //  加载状态
const queryFormRef = ref<FormInstance>();
const queryParams = reactive<chatListQuery>({
  pageNo: 1,
  pageSize: 10,
  visitorId: undefined as string | undefined,
  visitorName: undefined as string | undefined,
  serviceName: undefined as string | undefined,
  startTime: undefined as string | undefined,
  endTime: undefined as string | undefined,
  companyName: undefined as string | undefined
});
const dateTimeRange = ref<string[] | undefined>();
const total = ref(0); // 数据总数
const pageData = ref<chatListVO[]>(); // 分页数据

/**
 * 监听时间范围变化
 */
watch(dateTimeRange, (newVal) => {
  if (newVal) {
    [queryParams.startTime, queryParams.endTime] = newVal;
  } else {
    queryParams.startTime = undefined;
    queryParams.endTime = undefined;
  }
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getChatList(queryParams)
      .then(({ data }) => {
        console.log(data);
        pageData.value = data.list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

/**
 * 重置
 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  dateTimeRange.value = undefined;
  queryParams.visitorId = undefined;
  queryParams.visitorName = undefined;
  queryParams.serviceName = undefined;
  queryParams.startTime = undefined;
  queryParams.endTime = undefined;
  queryParams.companyName = undefined;
  queryParams.pageNo = 1; // 重置分页参数
  queryParams.pageSize = 10; // 重置分页参数
  handleQuery();
}

function handleDetail(row: chatListVO) {
  const { visitorId, serviceName } = row;
  if (!visitorId || !serviceName) return;
  console.log('Opening chat detail with:', { visitorId, serviceName });
  dialogVisible.value = true;
  selectedChat.value = { visitorId, serviceName };
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="访客ID" prop="visitorId">
          <el-input
              v-model="queryParams.visitorId"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="访客名称" prop="visitorName">
          <el-input
              v-model="queryParams.visitorName"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="客服名称" prop="serviceName">
          <el-input
              v-model="queryParams.serviceName"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="公司名称" prop="companyName">
          <el-input
              v-model="queryParams.companyName"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="最后聊天时间">
          <el-date-picker
              class="!w-[240px]"
              v-model="dateTimeRange"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"
          ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
          height="650"
          v-loading="loading"
          :data="pageData"
      >
        <el-table-column label="序号" align='center'>
          <template #default="scope">
            {{ ((queryParams.pageNo || 1) - 1) * (queryParams.pageSize || 10) + scope.$index + 1 }}
          </template>
        </el-table-column>

        <el-table-column
            key="visitorId"
            label="访客ID"
            align="center"
            prop="visitorId"
        />

        <el-table-column
            key="visitorName"
            label="访客名称"
            align="center"
            prop="visitorName"
        />

        <el-table-column
            key="serviceName"
            label="客服名称"
            align="center"
            prop="serviceName"
        />

        <el-table-column
            key="companyName"
            label="公司名称"
            align="center"
            prop="companyName"
        />

        <el-table-column
            key="lastMessageTime"
            label="最后聊天时间"
            align="center"
            prop="lastMessageTime"
        />

        <el-table-column
            key="totalMessageCount"
            label="总聊天条数"
            align="center"
            prop="totalMessageCount"
        />

        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="handleDetail(scope.row)"
            >
              聊天记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      title="聊天详情"
      width="60%"
      :destroy-on-close="true"
    >
      <chat-detail
        v-if="dialogVisible"
        :visitor-id="selectedChat.visitorId"
        :service-name="selectedChat.serviceName"
      />
    </el-dialog>
  </div>
</template>

<style scoped>

</style>